<?php

namespace app\home\controller\login;

use app\BaseController;
use app\common\model\HomeTokenModel;
use app\common\model\UserModel as models;
use app\common\traites\PublicCrudTrait;
use app\validate\home\Login as validates;
use think\exception\ValidateException;

class Login extends BaseController
{
    protected $model;
    use PublicCrudTrait;

    /**
     * 登陆
     */
    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //获取列表信息 登陆
    public function index()
    {
        //过滤数据
        $postField = 'phone,pwd';
        $post      = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('login')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }

        $find = $this->model->where(['user_name|phone' => $post['phone'], 'pwd' => pwdEncryption($post['pwd'])])->find();
        if (empty($find))
            return show([],config('ToConfig.http_code.error'),'账号或者密码错误');
        $find = $find->toArray();
        if ($find['status'] != 1)
            return show([],config('ToConfig.http_code.error'),'该用户被禁用');

        $find['token'] = $token = home_api_token($find['id']);

        //查询是否存在这条token的用户
        $update = (new HomeTokenModel())->where('user_id', $find['id'])->update(['token' => $token, 'create_time' => date('Y-m-d H:i:s')]);

        //数据不存在时插入
        if ($update == 0) {
            (new HomeTokenModel)->insert(['token' => $token, 'user_id' => $find['id'], 'create_time' => date('Y-m-d H:i:s')]);
        }

        //登陆成功后存入 session
        session('home_user', $find);
        (new \app\common\service\LoginLog())->login(2);//登陆日志
        return show($find);
    }

    //注册
    public function register()
    {
        //过滤数据
        $postField = 'phone,pwd,codes';
        $post      = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('register')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }
        //判断是否存在该账号
        $rand = userkey(rand(10, 20));//生成账号
        $find = $this->model->where('phone', $post['phone'])->whereOr('user_name', $rand)->find();
        if ($find) return show([],config('ToConfig.http_code.error'),'该手机号已存在');

        $data = [
            'phone' => $post['phone'],
            'nickname' => '新用户'.rand(1000,9999),
            'user_name' => $rand,
            'pwd' => pwdEncryption($post['pwd']),
            'create_time' => date('Y-m-d H:i:s'),
            'invitation_code'=>generateCode(),
            'type'=>2,
            'withdraw_pwd'=>home_tx_pwd(),
        ];

        //推广用户查询 //查询推广代理商
        if (isset($post['codes']) && !empty($post['codes'])) {
            $agent= $this->model->where('invitation_code', $post['codes'])->find();
            if ($agent){
                $data['agent_id_1']=$agent->id;
                $data['agent_id_2']=$agent->agent_id_1;
                $data['agent_id_3']=$agent->agent_id_2;
                $data['market_uid']=$agent->market_uid;
            }

        }
        //插入数据
        $find = $this->model->save($data);

        if (empty($find)) return show([],config('ToConfig.http_code.error'),'注册失败');
        return show();
    }

    //修改密码  获取用户信息在修改密码
    public function change_pwd()
    {
        //过滤数据
        $postField = 'pwd';
        $post      = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('edit_pwd')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }

        //插入数据 查询手机号和旧密码是否匹配
        $find = $this->model->where(['id' => session('home_user.id')])->save(['pwd' => pwdEncryption($post['pwd'])]);
        if (empty($find)) return show([],config('ToConfig.http_code.error'),'修改密码失败');
        return show();
    }

    //忘记密码
    public function forget()
    {
        //过滤数据
        $postField = 'phone,pwd';
        $post      = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('forget')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show([],config('ToConfig.http_code.error'),$e->getError());
        }

        //判断输入账号是否正确
        if ($post['phone'] != session('home_user.phone'))
            return show([],config('ToConfig.http_code.error'),'输入账号和登陆的不匹配');
        //插入数据
        $find = $this->model->where(['phone' => $post['phone']])->save(['pwd' => pwdEncryption($post['pwd'])]);
        if (empty($find)) return show([],config('ToConfig.http_code.error'),'修改密码失败');
        return show();
    }

    public function sign_out()
    {
        session('home_user', '');
        return show();
    }
}